<template>
  <div class="order-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="container mx-auto px-4 py-6">
        <h1 class="text-2xl font-bold text-gray-900">我的订单</h1>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <!-- 筛选工具栏 -->
      <div class="filter-toolbar">
        <div class="search-box">
          <el-input
            v-model="searchQuery"
            placeholder="搜索订单号/商品名称"
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <div class="filter-options">
          <el-select v-model="orderStatus" placeholder="订单状态" clearable>
            <el-option
              v-for="status in orderStatusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>

          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
          />
        </div>
      </div>

      <!-- 订单列表 -->
      <div class="order-list-content">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane
            v-for="tab in tabList"
            :key="tab.name"
            :label="tab.label"
            :name="tab.name"
          >
            <div class="orders-wrapper">
              <div
                v-for="order in filteredOrders"
                :key="order.id"
                class="order-card"
              >
                <!-- 订单头部 -->
                <div class="order-header">
                  <div class="order-info">
                    <span class="order-id">订单号：{{ order.orderNo }}</span>
                    <span class="order-date">{{
                      formatDate(order.createTime)
                    }}</span>
                  </div>
                  <div class="order-status">
                    <el-tag :type="getStatusType(order.status)">
                      {{ getStatusText(order.status) }}
                    </el-tag>
                  </div>
                </div>

                <!-- 订单商品 -->
                <div class="order-items">
                  <div
                    v-for="item in order.items"
                    :key="item.id"
                    class="order-item"
                    @click="handleItemClick(item)"
                  >
                    <el-image :src="item.image" class="item-image" />
                    <div class="item-info">
                      <div class="item-name">{{ item.name }}</div>
                      <div class="item-specs">{{ item.specs }}</div>
                      <div class="item-price">
                        <span class="price">¥{{ item.price }}</span>
                        <span class="quantity">x{{ item.quantity }}</span>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 订单底部 -->
                <div class="order-footer">
                  <div class="order-total">
                    共 {{ getTotalQuantity(order) }} 件商品 合计：<span
                      class="total-price"
                      >¥{{ order.totalAmount }}</span
                    >
                  </div>
                  <div class="order-actions">
                    <template v-if="order.status === 'pending_payment'">
                      <el-button type="primary" @click="handlePay(order)">
                        立即支付
                      </el-button>
                      <el-button @click="handleCancel(order)"
                        >取消订单</el-button
                      >
                    </template>

                    <template v-if="order.status === 'pending_delivery'">
                      <el-button @click="handleViewLogistics(order)">
                        查看物流
                      </el-button>
                    </template>

                    <template v-if="order.status === 'pending_receipt'">
                      <el-button
                        type="primary"
                        @click="handleConfirmReceipt(order)"
                      >
                        确认收货
                      </el-button>
                      <el-button @click="handleViewLogistics(order)">
                        查看物流
                      </el-button>
                    </template>

                    <template v-if="order.status === 'completed'">
                      <el-button type="primary" @click="handleReview(order)">
                        评价
                      </el-button>
                      <el-button @click="handleRebuy(order)"
                        >再次购买</el-button
                      >
                    </template>

                    <template v-if="order.status === 'cancelled'">
                      <el-button @click="handleDelete(order)"
                        >删除订单</el-button
                      >
                    </template>

                    <el-button @click="handleViewDetail(order)">
                      订单详情
                    </el-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :total="total"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import axios from "@/api/axios";

const router = useRouter();

// 搜索和筛选
const searchQuery = ref("");
const orderStatus = ref("");
const dateRange = ref(null);
const activeTab = ref("all");

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载状态
const loading = ref(false);

// 状态选项
const orderStatusOptions = [
  { label: "待付款", value: "pending_payment" },
  { label: "待发货", value: "pending_delivery" },
  { label: "待收货", value: "pending_receipt" },
  { label: "已完成", value: "completed" },
  { label: "已取消", value: "cancelled" },
];

// 标签页
const tabList = [
  { label: "全部订单", name: "all" },
  { label: "待付款", name: "pending_payment" },
  { label: "待发货", name: "pending_delivery" },
  { label: "待收货", name: "pending_receipt" },
  { label: "已完成", name: "completed" },
];

// 日期快捷选项
const dateShortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 订单数据
const orders = ref([]);
const allOrders = ref([]); // 存储所有订单数据，用于前端分页

// 获取订单数据
const fetchOrders = async () => {
  try {
    loading.value = true;
    
    // 构建查询参数
    const queryParams = {
      status: orderStatus.value || (activeTab.value !== 'all' ? activeTab.value : undefined),
    };
    
    // 如果有日期范围，添加到查询参数
    if (dateRange.value && dateRange.value.length === 2) {
      queryParams.startDate = dayjs(dateRange.value[0]).format('YYYY-MM-DD');
      queryParams.endDate = dayjs(dateRange.value[1]).format('YYYY-MM-DD');
    }
    
    // 如果有搜索关键词，添加到查询参数
    if (searchQuery.value) {
      queryParams.keyword = searchQuery.value;
    }
    
    try {
      const response = await axios.get('/user/orders', { params: queryParams });
      
      if (response && Array.isArray(response)) {
        allOrders.value = response;
        total.value = response.length;
        applyPagination();
        return;
      }
    } catch (error) {
      console.error("获取订单列表API失败:", error);
      // 发生错误，使用测试数据
    }
    
    // 使用测试数据
    allOrders.value = [
      {
        id: 1,
        orderNo: "GG20240315001",
        createTime: "2024-03-15 12:00:00",
        status: "pending_payment",
        items: [
          {
            id: 1,
            name: "贵港特色手工艺品",
            specs: "规格：标准款",
            price: 99,
            quantity: 2,
            image: "/images/products/product1.jpg",
          },
        ],
        totalAmount: 198,
      },
      {
        id: 2,
        orderNo: "GG20240314001",
        createTime: "2024-03-14 10:30:00",
        status: "pending_delivery",
        items: [
          {
            id: 2,
            name: "贵港特色小吃礼盒",
            specs: "规格：豪华款",
            price: 158,
            quantity: 1,
            image: "/images/products/product2.jpg",
          },
        ],
        totalAmount: 158,
      },
      {
        id: 3,
        orderNo: "GG20240310001",
        createTime: "2024-03-10 15:20:00",
        status: "pending_receipt",
        items: [
          {
            id: 3,
            name: "贵港文化艺术画册",
            specs: "规格：精装版",
            price: 128,
            quantity: 1,
            image: "/images/products/product3.jpg",
          },
        ],
        totalAmount: 128,
      },
      {
        id: 4,
        orderNo: "GG20240301001",
        createTime: "2024-03-01 09:15:00",
        status: "completed",
        items: [
          {
            id: 4,
            name: "贵港特色手工艺茶具",
            specs: "规格：家用套装",
            price: 299,
            quantity: 1,
            image: "/images/products/product4.jpg",
          },
        ],
        totalAmount: 299,
      },
      {
        id: 5,
        orderNo: "GG20240220001",
        createTime: "2024-02-20 14:30:00",
        status: "cancelled",
        items: [
          {
            id: 5,
            name: "贵港传统刺绣作品",
            specs: "规格：装饰画",
            price: 258,
            quantity: 1,
            image: "/images/products/product5.jpg",
          },
        ],
        totalAmount: 258,
      },
    ];
    
    total.value = allOrders.value.length;
    applyPagination();
  } catch (error) {
    console.error("获取订单列表失败:", error);
    ElMessage.error("获取订单列表失败");
  } finally {
    loading.value = false;
  }
};

// 应用前端分页
const applyPagination = () => {
  const filtered = filteredOrders.value;
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  orders.value = filtered.slice(start, end);
};

// 计算过滤后的订单
const filteredOrders = computed(() => {
  let result = [...allOrders.value];

  // 标签页过滤
  if (activeTab.value !== "all") {
    result = result.filter((order) => order.status === activeTab.value);
  }

  // 状态过滤
  if (orderStatus.value) {
    result = result.filter((order) => order.status === orderStatus.value);
  }

  // 日期过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const [start, end] = dateRange.value;
    result = result.filter((order) => {
      const orderDate = new Date(order.createTime);
      return orderDate >= start && orderDate <= end;
    });
  }

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(
      (order) =>
        order.orderNo.toLowerCase().includes(query) ||
        order.items.some((item) => item.name.toLowerCase().includes(query)),
    );
  }

  return result;
});

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
};

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    pending_payment: "warning",
    pending_delivery: "primary",
    pending_receipt: "success",
    completed: "info",
    cancelled: "danger",
  };
  return typeMap[status] || "default";
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending_payment: "待付款",
    pending_delivery: "待发货",
    pending_receipt: "待收货",
    completed: "已完成",
    cancelled: "已取消",
  };
  return textMap[status] || "未知状态";
};

// 计算订单总数量
const getTotalQuantity = (order) => {
  return order.items.reduce((total, item) => total + item.quantity, 0);
};

// 处理标签页切换
const handleTabClick = (tab) => {
  activeTab.value = tab.props.name;
  currentPage.value = 1;
  fetchOrders();
};

// 处理商品点击
const handleItemClick = (item) => {
  router.push(`/shop/product/${item.id}`);
};

// 处理支付
const handlePay = (order) => {
  router.push(`/order/payment/${order.id}`);
};

// 处理取消订单
const handleCancel = (order) => {
  ElMessageBox.confirm("确定要取消该订单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await axios.post(`/orders/${order.orderNo}/cancel`);
      ElMessage.success("订单已取消");
      fetchOrders(); // 重新加载订单
    } catch (error) {
      console.error("取消订单失败:", error);
      ElMessage.error("取消订单失败，请重试");
    }
  });
};

// 处理查看物流
const handleViewLogistics = (order) => {
  router.push(`/order/logistics/${order.id}`);
};

// 处理确认收货
const handleConfirmReceipt = (order) => {
  ElMessageBox.confirm("确认已收到商品？", "提示", {
    confirmButtonText: "确认收货",
    cancelButtonText: "取消",
    type: "info",
  }).then(async () => {
    try {
      await axios.post(`/orders/${order.orderNo}/confirm`);
      ElMessage.success("确认收货成功");
      fetchOrders(); // 重新加载订单
    } catch (error) {
      console.error("确认收货失败:", error);
      ElMessage.error("确认收货失败，请重试");
    }
  });
};

// 处理评价
const handleReview = (order) => {
  router.push(`/order/review/${order.id}`);
};

// 处理再次购买
const handleRebuy = (order) => {
  // 将商品添加到购物车
  if (!order.items || order.items.length === 0) {
    ElMessage.warning("没有可购买的商品");
    return;
  }
  
  // 尝试添加到购物车
  const addToCart = async () => {
    for (const item of order.items) {
      try {
        await axios.post('/cart/add', {
          productId: item.id,
          quantity: item.quantity
        });
      } catch (error) {
        console.error(`添加商品[${item.name}]到购物车失败:`, error);
        ElMessage.error(`添加商品[${item.name}]到购物车失败`);
        return false;
      }
    }
    return true;
  };
  
  addToCart().then(success => {
    if (success) {
      ElMessage.success("商品已添加到购物车");
      router.push("/shop/cart");
    }
  });
};

// 处理删除订单
const handleDelete = (order) => {
  ElMessageBox.confirm("确定要删除该订单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "danger",
  }).then(async () => {
    try {
      await axios.delete(`/orders/${order.orderNo}`);
      ElMessage.success("订单已删除");
      fetchOrders(); // 重新加载订单
    } catch (error) {
      console.error("删除订单失败:", error);
      ElMessage.error("删除订单失败");
    }
  });
};

// 处理查看详情
const handleViewDetail = (order) => {
  let routePath = '/order/detail';
  
  // 根据订单类型选择不同的详情页面
  if (order.type === 'hotel') {
    routePath = '/order/hotel-detail';
  } else if (order.type === 'ticket') {
    routePath = '/order/ticket-detail';
  } else if (order.type === 'experience') {
    routePath = '/order/experience-detail';
  } else if (order.type === 'guide') {
    routePath = '/order/guide-detail';
  }
  
  router.push(`${routePath}/${order.id}`);
};

// 处理分页
const handleSizeChange = (size) => {
  pageSize.value = size;
  applyPagination();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  applyPagination();
};

// 处理搜索和筛选变更
const handleFilterChange = () => {
  currentPage.value = 1;
  applyPagination();
};

// 监听筛选条件变化
watch([searchQuery, orderStatus, dateRange], () => {
  handleFilterChange();
}, { deep: true });

onMounted(() => {
  fetchOrders();
});
</script>

<style lang="scss" scoped>
.order-list {
  .page-header {
    @apply bg-white border-b border-gray-200;
  }

  .filter-toolbar {
    @apply flex items-center justify-between mb-6;

    .search-box {
      @apply w-80;
    }

    .filter-options {
      @apply flex items-center space-x-4;
    }
  }

  .order-list-content {
    @apply bg-white rounded-lg p-6;

    .orders-wrapper {
      @apply space-y-6;
    }

    .order-card {
      @apply border border-gray-200 rounded-lg overflow-hidden;

      .order-header {
        @apply flex items-center justify-between p-4 bg-gray-50 border-b border-gray-200;

        .order-info {
          @apply space-x-4 text-gray-500;

          .order-id {
            @apply font-medium text-gray-900;
          }
        }
      }

      .order-items {
        @apply divide-y divide-gray-100;

        .order-item {
          @apply flex items-center p-4 cursor-pointer hover:bg-gray-50 transition-colors;

          .item-image {
            @apply w-20 h-20 rounded;
          }

          .item-info {
            @apply ml-4 flex-1;

            .item-name {
              @apply font-medium mb-1;
            }

            .item-specs {
              @apply text-sm text-gray-500 mb-2;
            }

            .item-price {
              @apply flex items-center justify-between;

              .price {
                @apply text-primary-600 font-medium;
              }

              .quantity {
                @apply text-gray-500;
              }
            }
          }
        }
      }

      .order-footer {
        @apply flex items-center justify-between p-4 bg-gray-50 border-t border-gray-200;

        .order-total {
          @apply text-gray-500;

          .total-price {
            @apply text-xl font-medium text-primary-600 ml-2;
          }
        }

        .order-actions {
          @apply flex items-center space-x-2;
        }
      }
    }

    .pagination {
      @apply flex justify-center mt-8;
    }
  }
}
</style>
